<?php

namespace App\Http\Controllers\Guard\User;

use App\Http\Controllers\Common\GuardController;
use App\Imports\UserImport;
use App\Models\Constant\UserConstant;
use App\Models\User\User;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class UserController extends GuardController
{
    public function lst(Request $request) {
        $conditions = $request->input();
        $records = (new User())->getLst($conditions)->paginate($conditions['pageSize'],['*'],'page',$conditions['page']);

        foreach ($records as $record) {
            $record->type_name = UserConstant::MAP_TYPE[$record->type]??'未知';
        }

        return responseSuccess($records->items(),$records->total());
    }

    public function add(Request $request) {

        $this->validate($request, [
            'real_name'=>'required',
            'id_card'=>['required',
                'regex:/^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/'],
            'phone'=>'required|unique|regex:/^1[3456789]\d{9}$/',
            'age'=>'required|Integer',
            'type'=>'required|in:1,2,3',
        ],[],[
            'type'=>'身份类型'
        ]);
        $conditions = $request->input();
        $id = $request->input('id',0);
        $user = User::updateOrCreate(compact('id'),$conditions);
        return responseSuccess($user->toArray());
    }

    public function detail(Request $request) {
        $id = $request->input('id','');
        return $this->getRecordByIds(User::class, $id);
    }

    public function del(Request $request) {
        $id = $request->input('ids','');

        User::where(compact('id'))->forceDelete();


        return responseSuccess();
    }

    public function uploadUser(Request $request) {

        $file = $request->file('file');
        if(empty($file) || !$file->isValid()){
            return responseFail('文件无效！');
        }
        $path = $file->store('user','upload');
        $import = new UserImport();
        Excel::import($import, storage_path('app/public/upload/'.$path));

        if(count($import->existsPhones)>0){
            $msg = "下列手机号已存在！请检查后导入。".implode('，', $import->existsPhones);
            return responseFail($msg);
        }
        return responseSuccess();
    }



}
